﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using Autodesk.Revit.DB.Architecture;
using DataBase;

namespace DBService
{
	public class DbRoomInfo : DbObject
	{
		[Browsable(false)]
		public Guid Guid
		{
			get
			{
				return this.mGuid;
			}
			set
			{
				this.mGuid = value;
			}
		}

		[Category("属性")]
		[Description("房间Id")]
		[DisplayName("房间Id")]
		[ReadOnly(true)]
		public int RoomId
		{
			get
			{
				return this.mRoomId;
			}
		}

		[Category("属性")]
		[Description("房间名称")]
		[DisplayName("房间名称")]
		[ReadOnly(true)]
		public string Name
		{
			get
			{
				return this.mName;
			}
		}

		[Category("属性")]
		[Description("房间编号")]
		[DisplayName("房间编号")]
		[ReadOnly(true)]
		public string Number
		{
			get
			{
				return this.mNumber;
			}
		}

		[Category("属性")]
		[Description("房间功能")]
		[DisplayName("房间功能")]
		public string Function
		{
			get
			{
				return this.mFunction;
			}
			set
			{
				this.mFunction = value;
			}
		}

		[Category("属性")]
		[Description("房间材料")]
		[DisplayName("房间材料")]
		public string Material
		{
			get
			{
				return this.mMaterial;
			}
			set
			{
				this.mMaterial = value;
			}
		}

		[Category("属性")]
		[Description("房间高度")]
		[DisplayName("房间高度(mm)")]
		public double Height
		{
			get
			{
				return this.mHeight;
			}
			set
			{
				if (value.GetType() == typeof(double))
				{
					this.mHeight = value;
					return;
				}
				throw new Exception("输入的数据类型不匹配！");
			}
		}

		public DbRoomInfo(int projectId, Room room)
		{
            this.mName = room.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.ROOM_NAME).AsString();
			this.mNumber = room.Number;
			this.mRoomId = room.Id.IntegerValue;
			this.mProjectId = projectId;
            this.mHeight = double.Parse(room.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.ROOM_HEIGHT).AsValueString());
			this.mGuid = Guid.NewGuid();
		}

		public DbRoomInfo(int projectId, int roomId, string name, string number, string function, string material, double height)
		{
			this.mGuid = Guid.NewGuid();
			this.mProjectId = projectId;
			this.mName = name;
			this.mNumber = number;
			this.mFunction = function;
			this.mMaterial = material;
			this.mHeight = height;
			this.mRoomId = roomId;
		}

		public void RemoveFromXml(string fileName)
		{
			XmlUtils.RemoveRoomInfo(this.Guid, fileName);
		}

		public override void AddToDb(IDatabase db)
		{
			try
			{
				if (db.Connection.State == ConnectionState.Closed)
				{
					db.Connection.Open();
				}
				DbCommand dbCommand = db.Connection.CreateCommand();
				dbCommand.CommandText = string.Format("INSERT INTO tbroominfo (ProjectId,Name,Number,Height,[Function],Material,RoomId,Guid) VALUES ({0},'{1}','{2}',{3},'{4}','{5}',{6},{7})", new object[]
				{
					this.mProjectId,
					this.mName,
					this.mNumber,
					this.mHeight,
					this.mFunction,
					this.mMaterial,
					this.mRoomId,
					"@mID"
				});
				SqlParameter sqlParameter = new SqlParameter("@mID", SqlDbType.UniqueIdentifier);
				sqlParameter.Value = this.Guid;
				dbCommand.Parameters.Add(sqlParameter);
				dbCommand.ExecuteNonQuery();
				string sql = string.Format("select max(Id) from tbroominfo", Array.Empty<object>());
				DataTable dataTable = db.ExecQuery(sql);
				this.mId = Convert.ToInt32(dataTable.Rows[0][0]);
				this.mDatabase = db;
				if (db.Connection.State == ConnectionState.Open)
				{
					db.Connection.Close();
				}
			}
			catch (Exception ex)
			{
				if (db.Connection.State == ConnectionState.Open)
				{
					db.Connection.Close();
				}
				throw ex;
			}
		}

		public bool WirteToXML(string fileName)
		{
			return XmlUtils.AddRoonInfo(fileName, this);
		}

		public static List<DbRoomInfo> ReadFromXML(string fileName)
		{
			return XmlUtils.ReadRoomInfo(fileName);
		}

		public static DbRoomInfo ReadFromXML(Guid id, string fileName)
		{
			return XmlUtils.ReadRoomInfo(id, fileName);
		}

		public void UpdateToXML(string fileName)
		{
			XmlUtils.UpdateRoomInfoToXML(fileName, this);
		}

		public override void UpdateToDb()
		{
			try
			{
				if (base.Database.Connection.State == ConnectionState.Closed)
				{
					base.Database.Connection.Open();
				}
				DbCommand dbCommand = base.Database.Connection.CreateCommand();
				dbCommand.CommandText = string.Format("UPDATE tbroominfo SET ProjectId = {0},Name='{1}',Number='{2}',Height={3},[Function]='{4}',Material='{5}',RoomId={6} WHERE Guid ={7}", new object[]
				{
					this.mProjectId,
					this.mName,
					this.mNumber,
					this.mHeight,
					this.mFunction,
					this.mMaterial,
					this.mRoomId,
					"@id"
				});
				SqlParameter sqlParameter = new SqlParameter("@id", SqlDbType.UniqueIdentifier);
				sqlParameter.Value = this.Guid;
				dbCommand.Parameters.Add(sqlParameter);
				dbCommand.ExecuteNonQuery();
				if (base.Database.Connection.State == ConnectionState.Open)
				{
					base.Database.Connection.Close();
				}
			}
			catch (Exception ex)
			{
				if (base.Database.Connection.State == ConnectionState.Open)
				{
					base.Database.Connection.Close();
				}
				throw ex;
			}
		}

		public override void RemoveFromDb()
		{
			try
			{
				if (base.Database.Connection.State == ConnectionState.Closed)
				{
					base.Database.Connection.Open();
				}
				DbCommand dbCommand = base.Database.Connection.CreateCommand();
				dbCommand.CommandText = string.Format("DELETE FROM tbroominfo WHERE Guid = {0}", "@id");
				SqlParameter sqlParameter = new SqlParameter("@id", SqlDbType.UniqueIdentifier);
				sqlParameter.Value = this.Guid;
				dbCommand.Parameters.Add(sqlParameter);
				dbCommand.ExecuteNonQuery();
				if (base.Database.Connection.State == ConnectionState.Open)
				{
					base.Database.Connection.Close();
				}
			}
			catch (Exception ex)
			{
				if (base.Database.Connection.State == ConnectionState.Open)
				{
					base.Database.Connection.Close();
				}
				throw ex;
			}
		}

		public void Synchronous(Room room)
		{
			this.mName = room.Name;
			this.mNumber = room.Number;
		}

		public static DbRoomInfo GetByProject(DbProject project, int roomId)
		{
			DbRoomInfo result;
			try
			{
				if (project.Database.Connection.State == ConnectionState.Closed)
				{
					project.Database.Connection.Open();
				}
				string sql = string.Format("SELECT Id, ProjectId,Name,Number,Height,[Function],Material,RoomId,Guid FROM tbroominfo WHERE RoomId={0} AND ProjectId={1}", roomId, project.Id);
				DataTable dataTable = project.Database.ExecQuery(sql);
				if (project.Database.Connection.State == ConnectionState.Open)
				{
					project.Database.Connection.Close();
				}
				if (dataTable == null || dataTable.Rows.Count <= 0)
				{
					result = null;
				}
				else
				{
					int projectId = Convert.ToInt32(dataTable.Rows[0]["ProjectId"]);
					Guid guid = Guid.Parse(dataTable.Rows[0]["Guid"].ToString());
					int mId = Convert.ToInt32(dataTable.Rows[0]["Id"]);
					string name = Convert.ToString(dataTable.Rows[0]["Name"]);
					string number = Convert.ToString(dataTable.Rows[0]["Number"]);
					double height = Convert.ToDouble(dataTable.Rows[0]["Height"]);
					string function = Convert.ToString(dataTable.Rows[0]["Function"]);
					string material = Convert.ToString(dataTable.Rows[0]["Material"]);
					result = new DbRoomInfo(projectId, roomId, name, number, function, material, height)
					{
						mId = mId,
						mGuid = guid,
						mDatabase = project.Database
					};
				}
			}
			catch (Exception ex)
			{
				if (project.Database.Connection.State == ConnectionState.Open)
				{
					project.Database.Connection.Close();
				}
				throw ex;
			}
			return result;
		}

		public static List<DbRoomInfo> GetByProject(DbProject project)
		{
			List<DbRoomInfo> result;
			try
			{
				if (project.Database.Connection.State == ConnectionState.Closed)
				{
					project.Database.Connection.Open();
				}
				List<DbRoomInfo> list = new List<DbRoomInfo>();
				string sql = string.Format("SELECT Id, ProjectId,Name,Number,Height,[Function],Material,RoomId,Guid FROM tbroominfo WHERE ProjectId={0}", project.Id);
				DataTable dataTable = project.Database.ExecQuery(sql);
				if (project.Database.Connection.State == ConnectionState.Open)
				{
					project.Database.Connection.Close();
				}
				if (dataTable == null || dataTable.Rows.Count <= 0)
				{
					result = list;
				}
				else
				{
					for (int i = 0; i < dataTable.Rows.Count; i++)
					{
						int projectId = Convert.ToInt32(dataTable.Rows[i]["ProjectId"]);
						int roomId = Convert.ToInt32(dataTable.Rows[i]["RoomId"]);
						int mId = Convert.ToInt32(dataTable.Rows[i]["Id"]);
						Guid guid = Guid.Parse(dataTable.Rows[i]["Guid"].ToString());
						string name = Convert.ToString(dataTable.Rows[i]["Name"]);
						string number = Convert.ToString(dataTable.Rows[i]["Number"]);
						double height = Convert.ToDouble(dataTable.Rows[i]["Height"]);
						string function = Convert.ToString(dataTable.Rows[i]["Function"]);
						string material = Convert.ToString(dataTable.Rows[i]["Material"]);
						list.Add(new DbRoomInfo(projectId, roomId, name, number, function, material, height)
						{
							mId = mId,
							mGuid = guid,
							mDatabase = project.Database
						});
					}
					result = list;
				}
			}
			catch (Exception ex)
			{
				if (project.Database.Connection.State == ConnectionState.Open)
				{
					project.Database.Connection.Close();
				}
				throw ex;
			}
			return result;
		}

		public static DbRoomInfo GetFromDB(Guid id, BimServerDB db)
		{
			DbRoomInfo result;
			try
			{
				if (db.Connection.State == ConnectionState.Closed)
				{
					db.Connection.Open();
				}
				DbCommand dbCommand = db.Connection.CreateCommand();
				dbCommand.CommandText = string.Format("SELECT Id, ProjectId,Name,Number,Height,[Function],Material,RoomId FROM tbroominfo WHERE Guid={0}", "@id");
				SqlParameter sqlParameter = new SqlParameter("@id", SqlDbType.UniqueIdentifier);
				sqlParameter.Value = id;
				dbCommand.Parameters.Add(sqlParameter);
				IDataReader dataReader = dbCommand.ExecuteReader();
				DataTable dataTable = db.DataReaderToDataTable(dataReader);
				dataReader.Dispose();
				if (db.Connection.State == ConnectionState.Open)
				{
					db.Connection.Close();
				}
				if (dataTable == null)
				{
					result = null;
				}
				else
				{
					int projectId = Convert.ToInt32(dataTable.Rows[0]["ProjectId"]);
					int roomId = Convert.ToInt32(dataTable.Rows[0]["RoomId"]);
					string name = Convert.ToString(dataTable.Rows[0]["Name"]);
					string number = Convert.ToString(dataTable.Rows[0]["Number"]);
					double height = Convert.ToDouble(dataTable.Rows[0]["Height"]);
					string function = Convert.ToString(dataTable.Rows[0]["Function"]);
					string material = Convert.ToString(dataTable.Rows[0]["Material"]);
					result = new DbRoomInfo(projectId, roomId, name, number, function, material, height)
					{
						mGuid = id,
						mDatabase = db
					};
				}
			}
			catch (Exception ex)
			{
				if (db.Connection.State == ConnectionState.Open)
				{
					db.Connection.Close();
				}
				throw ex;
			}
			return result;
		}

		public override string ToString()
		{
			return this.Name;
		}

		private Guid mGuid;

		private int mProjectId;

		private int mRoomId;

		private string mName = "";

		private string mNumber = "";

		private string mFunction = "";

		private string mMaterial = "";

		private double mHeight;
	}
}
